package com.artisan.requestbodycache.filter;

import com.artisan.requestbodycache.wrapper.CachedHttpServletRequest;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Request Body 缓存过滤器
 * 职责：在过滤器链最前端拦截请求，包装为可重复读取的 Request
 */
public class CacheRequestFilter implements Filter {
    
    private static final Logger log = LoggerFactory.getLogger(CacheRequestFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 只处理 HTTP 请求
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            // 包装为可缓存的 Request
            CachedHttpServletRequest cachedRequest = new CachedHttpServletRequest(httpRequest);
            log.debug("Request Body 已缓存，URI: {}, Content-Length: {}", 
                httpRequest.getRequestURI(), 
                httpRequest.getContentLength());
            // 向后传递包装后的请求
            chain.doFilter(cachedRequest, response);
        } else {
            chain.doFilter(request, response);
        }
    }
}

